//
//  SecondViewController.m
//  Login
//
//  Created by FER on 22/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SecondViewController.h"
#import "ConnectionHTTP.h"
#import <CoreLocation/CoreLocation.h>
#import <MobileCoreServices/MobileCoreServices.h>


@implementation SecondViewController

@synthesize lm;
@synthesize imageView;
@synthesize coordinatesTextField;

@synthesize  popoverController;


NSMutableArray *listOfNews;
NSMutableArray *listOfNews_ID;




//Guardar
-(IBAction) btnGuardar: (id) sender;
{
    NSLog(@"Guardando");
  
    NSString *imageID =  [ConnectionHTTP uploadImage:imageView.image];
    
    NSLog(@"Image ID: %@",imageID);
    
    NSString *XMLBody = [NSString stringWithFormat:@"<REPORT>\n"
                          "<TITLE>%@</TITLE>\n"
                          "<DESCRIPTION>%@</DESCRIPTION>\n"
                          "<DATE>2011-11-0</DATE>\n"
                          "<USER_ID>1</USER_ID>\n"
                          "<COORDINATES> 21-18-02.54891 N 157-50-45.90280 W</COORDINATES>\n"
                          "<TYPE>1</TYPE>\n"
                          "<ADDRESS>%@</ADDRESS>\n"
                        "<imageID>%@</imageID> \n"
                          "<CARS>\n"
                          "<CAR>\n"
                          "<PLATE>%@</PLATE>\n"
                          "<BRAND>%@</BRAND>\n"
                          "<MODEL>%@</MODEL>\n"
                          "<YEAR>%@</YEAR>\n"
                          "<COLOR>%@</COLOR>\n"
                          "<DRIVER_ID>%@</DRIVER_ID>\n"
                          "<DRIVER_NAME>%@</DRIVER_NAME>\n"
                          "</CAR>\n"
                          "</CARS>\n"
                          "</REPORT>", textfieldTitle.text ,textfieldDescription.text,
                         textfieldAddress.text,imageID,textfieldPlaca.text,textfieldMarca.text,
                         textfieldModelo.text,textfieldAno.text,textfieldColor.text,
                         textfieldLicencia.text,textfieldConductor.text];
    
    //NSLog(@"%@",XMLBody);
    
   [ConnectionHTTP doRequestBody:(NSString *)@"ios/readReport.php":(NSString *)XMLBody];
   
}


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //mlabel.text=    [arrayNo objectAtIndex:row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [arrayTypes count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    return [arrayTypes objectAtIndex:row];
}

	// PAra las coordenadas geograficas

- (void) locationManager:(CLLocationManager *) manager 
			didUpdateToLocation:(CLLocation *) newLocation 
				fromLocation:(CLLocation *) oldLocation {
				
		//---display latitude---
		NSString *lat = [[NSString alloc] initWithFormat:@"%f", newLocation.coordinate.latitude];
		//latitudeTextField.text = lat;
		NSLog(@"LAT:%@",lat);
	
		//---display longitude---
		NSString *lng = [[NSString alloc] initWithFormat:@"%f", newLocation.coordinate.longitude];
		//longitudeTextField.text = lng;
		NSLog(@"LNG:%@",lng);
	
		//---display accuracy---
		NSString *acc = [[NSString alloc] initWithFormat:@"%f", newLocation.horizontalAccuracy];
		//accuracyTextField.text = acc;
		NSLog(@"ACC:%@",acc);
		
		NSString *coo = [NSString stringWithFormat:@"LAT: %@ LNG: %@",lat,lng];
		[coordinatesTextField setText:(NSString *)coo];
		coordinatesTextField.text = coo;
		[acc release]; 
		[lat release];
		[lng release];
	}
	
	- (void) locationManager:(CLLocationManager *) manager didFailWithError:(NSError *) error {
	
		NSString *msg = [[NSString alloc] initWithString:@"Error obtaining location"];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Done" otherButtonTitles:nil];
		[alert show]; 
		[msg release];
		[alert release];
	}
	// FIN -- Para las coordenadas geograficas


	//Para la camara
	
	- (IBAction) btnClicked: (id) sender{ 
		NSLog(@"Entro al boton!");
        
        UIImagePickerController *userPhotoPicker = [[UIImagePickerController alloc] init];
        [userPhotoPicker setDelegate:self];
        UIPopoverController *Pop = [[UIPopoverController alloc] initWithContentViewController:userPhotoPicker];
        
        [Pop setDelegate:self];
        [Pop presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        [userPhotoPicker release];
        
        }

	- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
    {
        NSLog(@"Guardar");
			imageView.image = image;
            [picker dismissModalViewControllerAnimated:YES];
	}

	- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { 
		NSLog(@"Cancel");
		[picker dismissModalViewControllerAnimated:YES];
	}

	- (NSString *) filePath: (NSString *) fileName { 
		NSArray *paths =
			NSSearchPathForDirectoriesInDomains( 
				NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDir = [paths objectAtIndex:0]; 
		return [documentsDir stringByAppendingPathComponent:fileName];
	}

	- (void) saveImage { 
		//---get the date from the ImageView--- 
		NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView.image)];
	
		//---write the date to file---
		[imageData writeToFile:[self filePath:@"MyPicture.png"] atomically:YES];
	
	}


	// FIN -- Para la camara


	
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	// Para las coordenadas geograficas
	
	self.lm = [[CLLocationManager alloc] init]; 
	lm.delegate = self; 
	lm.desiredAccuracy = kCLLocationAccuracyBest; 
	lm.distanceFilter = kCLDistanceFilterNone; 
	[lm startUpdatingLocation];
	
	// FIN -- Para las coordenadas geograficas
	
	arrayTypes = [[NSMutableArray alloc] init];
	
	NSString *newsURL = [NSString stringWithFormat:@"ios/getReportTypes.php"];
	NSString *newsResponse= [ConnectionHTTP doRequest:(NSString *)newsURL];
	
	//Parse XML
	xmlBuffer = [ [ newsResponse stringByReplacingOccurrencesOfString: @"<" withString :@"\n<" ] 
				 componentsSeparatedByCharactersInSet: [ NSCharacterSet newlineCharacterSet ] ];
	
	for(int i = 0; i < [ xmlBuffer count ]; i++) 
	{
		NSString *line = [ xmlBuffer objectAtIndex: i ];
		if ([ line hasPrefix: @"<TYPE>" ]) 
		{
			NSString *id_type;
			NSString *description;
			//NSString *date;
			
			while(!([ line isEqualToString: @"</TYPE>" ])) 
			{
				if ([ line hasPrefix: @"<ID>" ]) {
					id_type  = [ line stringByReplacingOccurrencesOfString: @"<ID>" withString: @"" ];		
				}
				if ([ line hasPrefix: @"<DESCRIPTION>" ]) 
				{
					description  = [ line stringByReplacingOccurrencesOfString: @"<DESCRIPTION>" withString: @"" ];		
				}
			
				i++;
				line = [ xmlBuffer objectAtIndex: i ];
			}
			//NSString *line= [NSString stringWithFormat:@"%@  DATE: %@",title,date];
			[arrayTypes addObject:description]; 
			//[listOfNews_ID addObject:id_news];
	
		}
	}
	
	

    //[arrayNo addObject:@" 100 "];
    //[arrayNo addObject:@" 200 "];
    //[arrayNo addObject:@" 400 "];
    //[arrayNo addObject:@" 600 "];
    //[arrayNo addObject:@" 1000 "];
    
    [pickerView selectRow:1 inComponent:0 animated:NO];
	
	[super viewDidLoad];
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[lm release];
	[imageView release];
	[imagePicker release];
    [super dealloc];
}

@end
